﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.X509;

namespace TempSpace
{
    class StreamsContainer : IDisposable
    {
        #region Output stream
        public System.IO.Stream outputstream { get; internal set; }
        #endregion

        #region Container for content Streams
        public List<System.IO.Stream> DontCrossTheStreams { get; private set; }

        public void AddStream(System.IO.Stream arg)
        {
            DontCrossTheStreams.Add(arg);
        }
        public void RemoveStream(System.IO.Stream arg)
        {
            try
            {
                DontCrossTheStreams.Remove(arg);
            }
            catch { 
            // no need to care about it not being there
            }
        }
        #endregion

        /// <summary>
        /// A sequence of information
        /// </summary>
        /// <returns>byte[] containing DER sequence of encoded streams</returns>

        public byte[] AsDer()
        {
            // To generate the sequence
            DerSequenceGenerator gen = new DerSequenceGenerator(outputstream);

            foreach(var i in DontCrossTheStreams) {
                var streambuffer=new byte[i.Length];
                i.Read(streambuffer,0,(int)i.Length);
                gen.AddObject(new DerOctetString(streambuffer));
            }
            gen.Close();
            byte[] output = new byte[outputstream.Length];
            outputstream.Seek(0, SeekOrigin.Begin);
            outputstream.Read(output,0,unchecked(Convert.ToInt32(outputstream.Length)));
            return output;
        }

        public StreamsContainer(string name = @"sequenceofoctetstrings.der")
        {
            if (null == name)
                outputstream = new System.IO.MemoryStream();
            else
            {
                // every one of these objects will overwrite the same file.
                new System.IO.FileStream(name, System.IO.FileMode.OpenOrCreate).Close();
                outputstream = new System.IO.FileStream(name, FileMode.Truncate);
            }

            DontCrossTheStreams = new List<System.IO.Stream>();
        }

        public void Dispose()
        {
            foreach (System.IO.Stream i in DontCrossTheStreams)
                i.Close();
            GC.SuppressFinalize(this);
        }
    }
}
